<?php

namespace App\Http\Controllers\ZHIHU\Systems;

use DB;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\ZHIHU\ApiController;
use App\Eloqumd\Zhihu\ZhihuMessage;
use App\Eloqumd\Zhihu\ZhihuSystemPublishMessage;
use App\Validate\Zhihu\ZhihuValidator;
use App\Jobs\SystemMessagePublishedNotify;

class MessageController extends ApiController
{
    static $listMessageRouteVerify = ['all', 'message', 'readed', 'deleted', 'sended', 'system', 'totals'];
    static $configMessageRouteVerify = ['toread', 'todelete', 'tomessage'];
    static $systemPublishMessageRouteVerify = ['list', 'create', 'edit', 'remove', 'publish', 'recopy'];

    // 管理员消息发布-list=消息发布列表-create=创建,edit=修改,remove=删除,publish=发布,recopy=复制
    public function systemPublishMessage(Request $request, $name = 'message')
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$systemPublishMessageRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "systemPublish" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 管理员消息发布【列表】
    public function systemPublishListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $input['keyword'] ?? '';
        $is_removed = $input['is_removed'] ?? '';
        $is_published = $input['is_published'] ?? '';
        $where = null;
        if ($is_removed != '') {
            $where[] = ['is_removed', '=', $is_removed, 'AND'];
        } else {
            $where[] = ['is_removed', '=', 0, 'AND'];
        }
        if ($is_published != '') {
            $where[] = ['is_published', '=', $is_published, 'AND'];
        }

        // 快捷搜索
        if ($keyword) {
            $where[] = ['title', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuSystemPublishMessage::where($where)->count();
        $listData = ZhihuSystemPublishMessage::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 管理员消息发布【添加】
    public function systemPublishCreateOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::systemPublishCreateOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuSystemPublishMessage;
            $model->title = $input['title'];
            $model->message = $input['message'];
            $model->message_type = $input['message_type'] == '' ? 'info' : $input['message_type'];
            $model->position = $input['position'] == '' ? 'bottom-right' : $input['position'];

            $model->duration = is_numeric($input['duration']) ? (int)$input['duration'] : 0;
            $model->types = $input['types'];
            if ($input['types'] == 0) {
                $model->times = '';
            } elseif ($input['types'] == 1) {
                $model->times = is_numeric($input['times']) ? (int)$input['times'] : 600;
            } elseif ($input['types'] == 2) {
                $model->times = $input['times'] == '' ? Carbon::now()->addMinutes(30) : $input['times'];
            }

            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 管理员消息发布【修改】
    public function systemPublishEditOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::systemPublishEditOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemPublishMessage::find($input['id']);
            $model->title = $input['title'];
            $model->message = $input['message'];
            $model->message_type = $input['message_type'] == '' ? 'info' : $input['message_type'];
            $model->position = $input['position'] == '' ? 'bottom-right' : $input['position'];

            $model->duration = is_numeric($input['duration']) ? (int)$input['duration'] : 0;
            $model->types = $input['types'];
            if ($input['types'] == 0) {
                $model->times = '';
            } elseif ($input['types'] == 1) {
                $model->times = is_numeric($input['times']) ? (int)$input['times'] : 600;
            } elseif ($input['types'] == 2) {
                $model->times = $input['times'] == '' ? Carbon::now()->addMinutes(30) : $input['times'];
            }

            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 管理员消息发布【删除】
    public function systemPublishRemoveOperation($input)
    {
        $id = $input['id'] ?? 0;
        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemPublishMessage::find($id);
            $model->is_removed = 1;
            $model->updated_at = Carbon::now();
            $model->removed_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'delete');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'delete');
        }
    }

    // 管理员消息发布【发布】
    public function systemPublishPublishOperation($input)
    {
        $id = $input['id'] ?? 0;
        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemPublishMessage::find($id);
            $model->is_published = 1;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            // 消息推送
            if ($model->types == 0) {
                $job = (new SystemMessagePublishedNotify($model->toArray()));
            } elseif ($model->types == 1) {
                $job = (new SystemMessagePublishedNotify($model->toArray()))->delay((int)$model->times);
            } else {
                $now = Carbon::now()->timestamp;
                $deal = strtotime($model->times);
                $second = abs($deal - $now);
                if (Carbon::now()->timestamp >= strtotime($model->times)) {
                    $job = (new SystemMessagePublishedNotify($model->toArray()));
                } else {
                    $job = (new SystemMessagePublishedNotify($model->toArray()))->delay($second);
                }
            }
            $this->dispatch($job);

            return $this->jsonReturns(10000, $this->success, null, 'published');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'published');
        }
    }

    // 管理员消息发布【复制】
    public function systemPublishRecopyOperation($input)
    {
        $id = $input['id'] ?? 0;
        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $old = ZhihuSystemPublishMessage::find($id);
            $model = new ZhihuSystemPublishMessage;
            $model->title = $old->title;
            $model->message = $old->message;
            $model->message_type = $old->message_type;
            $model->position = $old->position;
            $model->duration = $old->duration;
            $model->is_removed = 0;
            $model->is_published = 0;
            $model->types = $old->types;
            $model->times = $old->times;
            $model->removed_at = null;
            $model->created_at = Carbon::now();
            $model->updated_at = null;
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'copy');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'copy');
        }
    }

    // 站内信列表-私信列表
    public function listMessage(Request $request, $name = 'message')
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$listMessageRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        $where = $this->getMessageListCondtionOrEncryData($name, $request->all());

        $totalCount = ZhihuMessage::where($where)->count();
        if ($name == 'totals') {
            return $this->jsonReturns(10000, $this->success, ['totals' => $totalCount], 'get');
        }
        $listData = ZhihuMessage::where($where)
            ->orderBy('created_at', 'desc')
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 站内信操作
    public function configMessage(Request $request, $name)
    {
        if (!in_array($name, static::$configMessageRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        // 参数兼容数组和字符串
        $id = $request->input('id', '');
        if (!is_array($id)) {
            $id = explode(',', $id);
        }

        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $data = $this->getMessageListCondtionOrEncryData($name, $request->all());
            // 数据标记
            ZhihuMessage::whereIn('id', $id)->update($data);

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'msgopt');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'msgopt');
        }
    }

    // 获取列表条件或数据组装
    protected function getMessageListCondtionOrEncryData($name, $input)
    {
        $res = null;
        switch ($name) {
            case 'all':
                $res[] = ['to_id', '=', $this->apiUser['id'], 'AND'];
                $res[] = ['status', '<>', 2, 'AND'];
                break;
            case 'totals':
            case 'message':
                $res[] = ['to_id', '=', $this->apiUser['id'], 'AND'];
                $res[] = ['status', '=', 0, 'AND'];
                break;
            case 'readed':
                $res[] = ['to_id', '=', $this->apiUser['id'], 'AND'];
                $res[] = ['status', '=', 1, 'AND'];
                break;
            case 'deleted':
                $res[] = ['to_id', '=', $this->apiUser['id'], 'AND'];
                $res[] = ['status', '=', 2, 'AND'];
                break;
            case 'sended':
                $res[] = ['from_id', '=', $this->apiUser['id'], 'AND'];
                break;
            case 'system':
                $res[] = ['to_id', '=', $this->apiUser['id'], 'AND'];
                $res[] = ['is_system', '=', 1, 'AND'];
                break;
            case 'toread':
                $res['status'] = 1;
                $res['readed_at'] = Carbon::now();
                $res['updated_at'] = Carbon::now();
                break;
            case 'todelete':
                $res['status'] = 2;
                $res['removed_at'] = Carbon::now();
                $res['updated_at'] = Carbon::now();
                break;
            case 'tomessage':
                $res['status'] = 0;
                $res['readed_at'] = null;
                $res['updated_at'] = Carbon::now();
                break;
            default:
                break;
        }

        return $res;
    }
}
